/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package media_server;
import com.sun.org.apache.xerces.internal.parsers.DOMParser;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Attr;
import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
 *
 * @author Maytinh
 */
public class CreateXmlFile_Client {
   public static Document document=null;
     public Document getDocument()
     {
        return document;
     }
     public CreateXmlFile_Client(String S_Ip,String S_NickName,String S_LogIn,String S_Active)
     {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try
        {
          DocumentBuilder builder = factory.newDocumentBuilder();
          document = builder.newDocument();
        }
        catch (ParserConfigurationException parserException)
        {
        }
         Element root = document.createElement("Clients");
         document.appendChild(root);


        // add comment to XML document
        Comment simpleComment = document.createComment("Danh sach cac Client");
        root.appendChild(simpleComment);

        // add child element
        Node contactNode = createContactNode(document,S_Ip,S_NickName,S_Active,S_LogIn);
        root.appendChild(contactNode);


        // write the XML document to disk
        try {

          // create DOMSource for source XML document
          Source xmlSource = new DOMSource(document);

          // create StreamResult for transformation result
          Result result = new StreamResult(new FileOutputStream("Client.xml"));

          // create TransformerFactory
          TransformerFactory transformerFactory = TransformerFactory.newInstance();

          // create Transformer for transformation
          Transformer transformer = transformerFactory.newTransformer();

          transformer.setOutputProperty("indent", "yes");

          // transform and deliver content to client
          transformer.transform(xmlSource, result);
        }

        // handle exception creating TransformerFactory
        catch (TransformerFactoryConfigurationError factoryError) {
          System.err.println("Error creating " + "TransformerFactory");
        }catch (TransformerException transformerError) {
          System.err.println("Error transforming document");
        }    catch (IOException ioException) {
        }
    }
      public static void CreateXmlFile_Client(String uri,Document document,String S_Ip)
     {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try
        {
          DocumentBuilder builder = factory.newDocumentBuilder();
          document = builder.newDocument();
        }
        catch (ParserConfigurationException parserException)
        {
        }
         Element root = document.createElement("Clients");

         Element client = document.createElement("Client");
          Attr genderAttribute = document.createAttribute("Ip");
        genderAttribute.setValue(S_Ip);
         // append attribute to contact element
        client.setAttributeNode(genderAttribute);

        root.appendChild(client);
        document.appendChild(root);




        // write the XML document to disk
        try {

          // create DOMSource for source XML document
          Source xmlSource = new DOMSource(document);

          // create StreamResult for transformation result
          Result result = new StreamResult(new FileOutputStream("Client.xml"));

          // create TransformerFactory
          TransformerFactory transformerFactory = TransformerFactory.newInstance();

          // create Transformer for transformation
          Transformer transformer = transformerFactory.newTransformer();

          transformer.setOutputProperty("indent", "yes");

          // transform and deliver content to client
          transformer.transform(xmlSource, result);
        }

        // handle exception creating TransformerFactory
        catch (TransformerFactoryConfigurationError factoryError) {
          System.err.println("Error creating " + "TransformerFactory");
        }catch (TransformerException transformerError) {
          System.err.println("Error transforming document");
        }    catch (IOException ioException) {
        }
    }
       public CreateXmlFile_Client()
     {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try
        {
          DocumentBuilder builder = factory.newDocumentBuilder();
          document = builder.newDocument();
        }
        catch (ParserConfigurationException parserException)
        {
        }
         Element root = document.createElement("Clients");


        document.appendChild(root);

        // write the XML document to disk
        try {

          // create DOMSource for source XML document
          Source xmlSource = new DOMSource(document);

          // create StreamResult for transformation result
          Result result = new StreamResult(new FileOutputStream("Client.xml"));

          // create TransformerFactory
          TransformerFactory transformerFactory = TransformerFactory.newInstance();

          // create Transformer for transformation
          Transformer transformer = transformerFactory.newTransformer();

          transformer.setOutputProperty("indent", "yes");

          // transform and deliver content to client
          transformer.transform(xmlSource, result);
        }

        // handle exception creating TransformerFactory
        catch (TransformerFactoryConfigurationError factoryError) {
          System.err.println("Error creating " + "TransformerFactory");
        }catch (TransformerException transformerError) {
          System.err.println("Error transforming document");
        }    catch (IOException ioException) {
        }
    }
     public static Node createContactNode(Document document,String S_Ip,String S_NickName,String S_Active,String S_LogIn)
     {

        // create FirstName and LastName elements
        Element client = document.createElement("Client");
         // create attribute
        Attr genderAttribute1 = document.createAttribute("Ip");
        genderAttribute1.setValue(S_Ip);
         // append attribute to contact element
        client.setAttributeNode(genderAttribute1);

        Element nickname= document.createElement("NickName");
        Element login= document.createElement("LogIn");
        Element active= document.createElement("Active");
        nickname.appendChild(document.createTextNode(S_NickName));
        login.appendChild(document.createTextNode(S_LogIn));
        active.appendChild(document.createTextNode(S_Active));

        client.appendChild(nickname);
        client.appendChild(login);
        client.appendChild(active);

        return client;
  }


    String searchFor;
    public static void AddNodeDocument(String uri,Document document,String S_Ip,String S_NickName,String S_Active,String S_LogIn)
    {


        int n=0;
        DOMParser parer = new DOMParser();
        try
        {
            parer.parse(uri);
            document=(Document)parer.getDocument();

            NodeList node=document.getElementsByTagName("Client");
           NodeList root=document.getElementsByTagName("Clients");
            if(node!=null)
            {
                for(int i=0;i<node.getLength();i++)
                {
                    if(S_Ip!=null)
                    {
                         if(node.item(i).getAttributes().item(0).getNodeValue().equals(S_Ip))
                         {
                            if(node.item(i).getChildNodes().item(0).getNodeName().equals("NickName")
                                    || node.item(i).getChildNodes().item(0).getNodeName().equals("LogIn")
                                    || node.item(i).getChildNodes().item(0).getNodeName().equals("Active"))
                            {
                                xoa(S_Ip);
                                Element nickname = document.createElement("NickName");
                                nickname.appendChild(document.createTextNode(S_NickName));
                                Element login= document.createElement("LogIn");
                                login.appendChild(document.createTextNode(S_LogIn));
                                Element active= document.createElement("Active");
                                active.appendChild(document.createTextNode(S_Active));


                                // create contact element
                                Element contact = document.createElement("Client");

                                // create attribute
                                Attr genderAttribute = document.createAttribute("Ip");
                                genderAttribute.setValue(S_Ip);
                                 // append attribute to contact element
                                contact.setAttributeNode(genderAttribute);

                                contact.appendChild(nickname);
                                contact.appendChild(login);
                                contact.appendChild(active);

                                root.item(0).appendChild(contact);
                             }
                            else
                            {
                                 Element nickname = document.createElement("NickName");
                                nickname.appendChild(document.createTextNode(S_NickName));

                                Element login= document.createElement("LogIn");
                                login.appendChild(document.createTextNode(S_LogIn));
                                Element active= document.createElement("Active");
                                active.appendChild(document.createTextNode(S_Active));
                                node.item(i).appendChild(nickname);

                                node.item(i).appendChild(login);
                                node.item(i).appendChild(active);
                            }

                         }
                         else
                         {
                             n++;
                         }
                          // write the XML document to disk
                        try
                        {

                          // create DOMSource for source XML document
                          Source xmlSource = new DOMSource(document);

                          // create StreamResult for transformation result
                          Result result = new StreamResult(new FileOutputStream("Client.xml"));

                          // create TransformerFactory
                          TransformerFactory transformerFactory = TransformerFactory.newInstance();

                          // create Transformer for transformation
                          Transformer transformer = transformerFactory.newTransformer();

                          transformer.setOutputProperty("indent", "yes");

                          // transform and deliver content to client
                          transformer.transform(xmlSource, result);
                        }

                        // handle exception creating TransformerFactory
                        catch (TransformerFactoryConfigurationError factoryError)
                        {
                          System.err.println("Error creating " + "TransformerFactory");

                        }
                        catch (TransformerException transformerError)
                        {
                          System.err.println("Error transforming document");

                        }
                        catch (IOException ioException)
                        {

                        }

                    }
                }
                 if(n==node.getLength())
                 {

                      // create FirstName and LastName elements

                        Element nickname = document.createElement("NickName");
                        nickname.appendChild(document.createTextNode(S_NickName));
                        Element login= document.createElement("LogIn");
                        login.appendChild(document.createTextNode(S_LogIn));
                        Element active= document.createElement("Active");
                        active.appendChild(document.createTextNode(S_Active));


                        // create contact element
                        Element contact = document.createElement("Client");

                        // create attribute
                        Attr genderAttribute = document.createAttribute("Ip");
                        genderAttribute.setValue(S_Ip);
                         // append attribute to contact element
                        contact.setAttributeNode(genderAttribute);

                        contact.appendChild(nickname);
                        contact.appendChild(login);
                        contact.appendChild(active);

                        root.item(0).appendChild(contact);


                         // write the XML document to disk
                        try
                        {

                          // create DOMSource for source XML document
                          Source xmlSource = new DOMSource(document);

                          // create StreamResult for transformation result
                          Result result = new StreamResult(new FileOutputStream("Client.xml"));

                          // create TransformerFactory
                          TransformerFactory transformerFactory = TransformerFactory.newInstance();

                          // create Transformer for transformation
                          Transformer transformer = transformerFactory.newTransformer();

                          transformer.setOutputProperty("indent", "yes");

                          // transform and deliver content to client
                          transformer.transform(xmlSource, result);
                        }

                        // handle exception creating TransformerFactory
                        catch (TransformerFactoryConfigurationError factoryError)
                        {
                          System.err.println("Error creating " + "TransformerFactory");

                        }
                        catch (TransformerException transformerError)
                        {
                          System.err.println("Error transforming document");
                        }
                        catch (IOException ioException)
                        {
                        }


                 }


            }

        }
        catch (SAXException ex)
        {

        }
        catch (IOException ex)
        {

        }

    }

     public static void AddNodeDocument_Attri(String uri,Document document,String S_NickName,String S_Ip,String S_LogIn,String S_Active)
    {

        DOMParser parer = new DOMParser();
        try
        {
            parer.parse(uri);
            document=(Document)parer.getDocument();
            NodeList n= document.getElementsByTagName("Client");

            for(int i=0;i<n.getLength(); i++)
            {

                if(n.item(i).getAttributes().item(0).getNodeValue().equals(S_Ip))
                {
                  for(int j=0;j<n.item(i).getChildNodes().getLength();j++)
                    {
                        Node e=n.item(i).getChildNodes().item(j);
                        if(e.getNodeType()==e.ELEMENT_NODE)
                        {
                            e.getParentNode().removeChild(e);
                        }
                        try {

                              // create DOMSource for source XML document
                              Source xmlSource = new DOMSource(document);

                              // create StreamResult for transformation result
                              Result result = new StreamResult(new FileOutputStream("Client.xml"));

                              // create TransformerFactory
                              TransformerFactory transformerFactory = TransformerFactory.newInstance();

                              // create Transformer for transformation
                              Transformer transformer = transformerFactory.newTransformer();

                              transformer.setOutputProperty("indent", "yes");

                              // transform and deliver content to client
                              transformer.transform(xmlSource, result);
                            }

                            // handle exception creating TransformerFactory
                            catch (TransformerFactoryConfigurationError factoryError)
                            {
                              System.err.println("Error creating " + "TransformerFactory");
                            }
                            catch (TransformerException transformerError)
                            {
                              System.err.println("Error transforming document");
                            }
                            catch (IOException ioException)
                            {
                            }
                    }
                     // append attribute to contact element
//                    Element nickname =(Element)n.item(i);
//                    Element login =(Element)n.item(i);
//                    Element active =(Element)n.item(i);
//
//                    nickname.appendChild(document.createTextNode(S_NickName));
//                    login.appendChild(document.createTextNode(S_LogIn));
//                    active.appendChild(document.createTextNode(S_Active));
//
//                    n.item(i).appendChild(login);
//                    n.item(i).appendChild(nickname);
//                    n.item(i).appendChild(active);
                    xoa(S_Ip);
                    Element nickname = document.createElement("NickName");
                    nickname.appendChild(document.createTextNode(S_NickName));

                    Element login= document.createElement("LogIn");
                    login.appendChild(document.createTextNode(S_LogIn));
                    Element active= document.createElement("Active");
                    active.appendChild(document.createTextNode(S_Active));
                    n.item(i).appendChild(nickname);

                    n.item(i).appendChild(login);
                    n.item(i).appendChild(active);
                    // write the XML document to disk
                    try
                    {

                      // create DOMSource for source XML document
                      Source xmlSource = new DOMSource(document);

                      // create StreamResult for transformation result
                      Result result = new StreamResult(new FileOutputStream("Client.xml"));

                      // create TransformerFactory
                      TransformerFactory transformerFactory = TransformerFactory.newInstance();

                      // create Transformer for transformation
                      Transformer transformer = transformerFactory.newTransformer();

                      transformer.setOutputProperty("indent", "yes");

                      // transform and deliver content to client
                      transformer.transform(xmlSource, result);
                    }

                    // handle exception creating TransformerFactory
                    catch (TransformerFactoryConfigurationError factoryError)
                    {
                      System.err.println("Error creating " + "TransformerFactory");
                    }
                    catch (TransformerException transformerError)
                    {
                      System.err.println("Error transforming document");
                    }
                    catch (IOException ioException)
                    {
                    }

             }

          }
        }
        catch (SAXException ex)
        {

        }
        catch (IOException ex)
        {

        }
    }

     public static boolean kiemTraIP(String S_ip)
    {
        DOMParser parer = new DOMParser();
        try {
            parer.parse("Client.xml");
        }
        catch (SAXException ex) {
            Logger.getLogger(CreateXmlFile_Client.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex)
        {
            Logger.getLogger(CreateXmlFile_Client.class.getName()).log(Level.SEVERE, null, ex);
        }
            document=(Document)parer.getDocument();
            NodeList n= document.getElementsByTagName("Client");
            NodeList root= document.getElementsByTagName("Clients");

            for(int i=0;i<n.getLength(); i++)
            {
                if(n.item(i).getAttributes().item(0).getNodeValue().toLowerCase().equals(S_ip))
                {
                  return true;
                }
            }
         return false;
   }

      public static int kiemTraDuocPhepKetNoi(String S_ip)
    {
        DOMParser parer = new DOMParser();
        int flag=0;
        int k = 0;
        try {
            parer.parse("Client.xml");
        }
        catch (SAXException ex)
        {
            Logger.getLogger(CreateXmlFile_Client.class.getName()).log(Level.SEVERE, null, ex);
        }
        catch (IOException ex)
        {
            Logger.getLogger(CreateXmlFile_Client.class.getName()).log(Level.SEVERE, null, ex);
        }
            document=(Document)parer.getDocument();


            String root1=  document.getDocumentElement().getNodeName();

            if(root1.equals("Clients"))
            {

                NodeList root = document.getElementsByTagName("Clients");
                NodeList n= document.getElementsByTagName("Client");
                if(root.getLength()>0)
                {
                        for(int i=0;i<n.getLength(); i++)
                        {
                            //System.out.println(n.item(i).getChildNodes().item(4).getNextSibling().getTextContent());
                            if(n.item(i).getAttributes().item(0).getNodeValue().equals(S_ip))
                            {
                                flag = 1;
                                k = i;
                                break;
                            }
                        }
                        if(flag==1)
                        {
                              if(n.item(k).getChildNodes().item(5).getTextContent().equals("1"))
                              {
                                 // System.out.println(n.item(k).getChildNodes().item(1).getTextContent());
                                  return 1;
                                }
                              else
                              {
                                  //System.out.println(n.item(k).getChildNodes().item(3).getTextContent());
                                  return 0;
                              }
                        }
                        else
                            return 2;
                }
                else
                {
                    return 2;
                }
            }
            //System.out.println("12");
         return 0;
   }
     public static void xoa(String S_Ip)
    {
         DOMParser parer = new DOMParser();
        try
        {
            parer.parse("Client.xml");
        } catch (SAXException ex) {
            Logger.getLogger(CreateXmlFile_Client.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(CreateXmlFile_Client.class.getName()).log(Level.SEVERE, null, ex);
        }
        document=(Document)parer.getDocument();
        NodeList n= document.getElementsByTagName("Client");
         for(int i=0;i<n.getLength(); i++)
        {
            if(n.item(i).getAttributes().item(0).getNodeValue().equals(S_Ip))
            {

                    for(int j=0;j<n.item(i).getChildNodes().getLength();j++)
                    {

                        Node e=n.item(i).getChildNodes().item(j);
                        if(e.getNodeType()==e.ELEMENT_NODE)
                        {
                            e.getParentNode().removeChild(e);
                        }
                      //System.out.println(e.getNodeName());
                         try {

                              // create DOMSource for source XML document
                              Source xmlSource = new DOMSource(document);

                              // create StreamResult for transformation result
                              Result result = new StreamResult(new FileOutputStream("Client.xml"));

                              // create TransformerFactory
                              TransformerFactory transformerFactory = TransformerFactory.newInstance();

                              // create Transformer for transformation
                              Transformer transformer = transformerFactory.newTransformer();

                              transformer.setOutputProperty("indent", "yes");

                              // transform and deliver content to client
                              transformer.transform(xmlSource, result);
                            }

                            // handle exception creating TransformerFactory
                            catch (TransformerFactoryConfigurationError factoryError)
                            {
                              System.err.println("Error creating " + "TransformerFactory");
                            }
                            catch (TransformerException transformerError)
                            {
                              System.err.println("Error transforming document");
                            }
                            catch (IOException ioException)
                            {
                            }
                    }

            }
        }
    }

    public static int SoClientTruyCapMotKenh(String S_Port)
    {
         int SoClient=0;
          DOMParser parer = new DOMParser();
        try {
            parer.parse("Client.xml");
        } catch (SAXException ex) {
            Logger.getLogger(CreateXmlFile_Client.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(CreateXmlFile_Client.class.getName()).log(Level.SEVERE, null, ex);
        }
            document=(Document)parer.getDocument();
            NodeList n= document.getElementsByTagName("Client");

            for(int i=0;i<n.getLength(); i++)
            {
                if(n.item(i).getChildNodes().item(2).getNodeValue().equals(S_Port))
                {
                    SoClient ++;
                }
            }
         return SoClient;
     }
     public static int SoClientTruyCap(String S)
    {
         int SoClient=0;
          DOMParser parer = new DOMParser();
        try {
            parer.parse("Client.xml");
        } catch (SAXException ex) {
            Logger.getLogger(CreateXmlFile_Client.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(CreateXmlFile_Client.class.getName()).log(Level.SEVERE, null, ex);
        }
            document=(Document)parer.getDocument();
            NodeList n= document.getElementsByTagName("Clients");

            for(int i=0;i<n.getLength(); i++)
            {
                if(n.item(i).getChildNodes().item(i).getNodeName().equals(S))
                {
                    SoClient ++;
                }
            }
         return SoClient;
     }
       public static void AddNodeDocument_Attri_LogOut(String uri,Document document,String S_NickName,String S_Ip,String S_LogIn,String S_Active)
    {

        DOMParser parer = new DOMParser();
        try
        {
            parer.parse(uri);
            document=(Document)parer.getDocument();
            NodeList n= document.getElementsByTagName("Client");

            for(int i=0;i<n.getLength(); i++)
            {

                if(n.item(i).getAttributes().item(0).getNodeValue().equals(S_Ip))
                {
                  for(int j=0;j<n.item(i).getChildNodes().getLength();j++)
                    {
                        Node e=n.item(i).getChildNodes().item(j);
                        if(e.getNodeName().equals("NickName"))
                            S_NickName=e.getTextContent().trim();
                        if(e.getNodeType()==e.ELEMENT_NODE)
                        {
                            e.getParentNode().removeChild(e);
                        }
                        try {

                              // create DOMSource for source XML document
                              Source xmlSource = new DOMSource(document);

                              // create StreamResult for transformation result
                              Result result = new StreamResult(new FileOutputStream("Client.xml"));

                              // create TransformerFactory
                              TransformerFactory transformerFactory = TransformerFactory.newInstance();

                              // create Transformer for transformation
                              Transformer transformer = transformerFactory.newTransformer();

                              transformer.setOutputProperty("indent", "yes");

                              // transform and deliver content to client
                              transformer.transform(xmlSource, result);
                            }

                            // handle exception creating TransformerFactory
                            catch (TransformerFactoryConfigurationError factoryError)
                            {
                              System.err.println("Error creating " + "TransformerFactory");
                            }
                            catch (TransformerException transformerError)
                            {
                              System.err.println("Error transforming document");
                            }
                            catch (IOException ioException)
                            {
                            }
                    }
                    xoa(S_Ip);
                    Element nickname = document.createElement("NickName");
                    nickname.appendChild(document.createTextNode(S_NickName));

                    Element login= document.createElement("LogIn");
                    login.appendChild(document.createTextNode(S_LogIn));
                    Element active= document.createElement("Active");
                    active.appendChild(document.createTextNode(S_Active));
                    n.item(i).appendChild(nickname);

                    n.item(i).appendChild(login);
                    n.item(i).appendChild(active);
                    // write the XML document to disk
                    try
                    {

                      // create DOMSource for source XML document
                      Source xmlSource = new DOMSource(document);

                      // create StreamResult for transformation result
                      Result result = new StreamResult(new FileOutputStream("Client.xml"));

                      // create TransformerFactory
                      TransformerFactory transformerFactory = TransformerFactory.newInstance();

                      // create Transformer for transformation
                      Transformer transformer = transformerFactory.newTransformer();

                      transformer.setOutputProperty("indent", "yes");

                      // transform and deliver content to client
                      transformer.transform(xmlSource, result);
                    }

                    // handle exception creating TransformerFactory
                    catch (TransformerFactoryConfigurationError factoryError)
                    {
                      System.err.println("Error creating " + "TransformerFactory");
                    }
                    catch (TransformerException transformerError)
                    {
                      System.err.println("Error transforming document");
                    }
                    catch (IOException ioException)
                    {
                    }

             }

          }
        }
        catch (SAXException ex)
        {

        }
        catch (IOException ex)
        {

        }
    }
}
